<script lang="ts" setup>
import { ref } from 'vue';

import {
  VbenButton,
  VbenModal,
} from '@vben/common-ui';

import { Form } from 'ant-design-vue';

import { UploadOutlined } from '@ant-design/icons-vue';
import { Alert, Descriptions, DescriptionsItem, message, Upload } from 'ant-design-vue';
import { VxeGrid } from 'vxe-table';

import { downloadBOMTemplate, importBOM } from '#/api/bom/bom';

// 定义props
interface Props {
  visible: boolean;
}

// 定义emits
interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success', data: any): void;
  (e: 'error', error: any): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 状态
const loading = ref(false);
const fileList = ref<any[]>([]);
const previewData = ref<any[]>([]);

// 预览表格配置
const previewGridOptions = {
  columns: [
    { field: 'bom_code', title: 'BOM编码', width: 150 },
    { field: 'bom_name', title: 'BOM名称', width: 200 },
    { field: 'product_code', title: '产品编码', width: 150 },
    { field: 'version', title: '版本', width: 100 },
    { field: 'bom_type', title: 'BOM类型', width: 120 },
    { field: 'status', title: '状态', width: 100 },
  ],
  pagerConfig: {
    enabled: false,
  },
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};

// 上传前校验
const beforeUpload = (file) => {
  const isExcel =
    file.type ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel';

  if (!isExcel) {
    message.error('只能上传Excel文件!');
    return false;
  }

  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
    return false;
  }

  return false; // 阻止自动上传
};

// 自定义上传请求
const customRequest = async ({ file }) => {
  try {
    loading.value = true;

    // 这里可以添加文件解析逻辑，生成预览数据
    // 实际项目中可能需要使用xlsx等库解析Excel文件
    // 这里仅作示例，模拟解析结果
    const mockData = [
      {
        bom_code: 'BOM001',
        bom_name: '产品A的BOM',
        product_code: 'PROD001',
        version: '1.0',
        bom_type: 'production',
        status: 'draft',
      },
      {
        bom_code: 'BOM002',
        bom_name: '产品B的BOM',
        product_code: 'PROD002',
        version: '1.0',
        bom_type: 'production',
        status: 'draft',
      },
    ];

    previewData.value = mockData.slice(0, 10); // 只显示前10条
    message.success('文件解析成功');
  } catch (error) {
    message.error('文件解析失败');
    previewData.value = [];
  } finally {
    loading.value = false;
  }
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const { data } = await downloadBOMTemplate();
    // 处理文件下载
    const blob = new Blob([data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `bom_import_template.xlsx`;
    link.click();
    window.URL.revokeObjectURL(url);
    message.success('模板下载成功');
  } catch (error) {
    message.error('模板下载失败');
  }
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
  // 重置状态
  fileList.value = [];
  previewData.value = [];
};

// 确认导入
const handleConfirm = async () => {
  if (fileList.value.length === 0) {
    message.warning('请选择要导入的文件');
    return;
  }

  try {
    loading.value = true;
    const formData = new FormData();
    formData.append('file', fileList.value[0]);

    const data = await importBOM(formData);

    // 传递导入结果数据
    emit('success', {
      success_count: data.success_count,
      fail_count: data.fail_count,
      error_report_url: data.error_report_url,
    });

    // 关闭弹窗
    emit('update:visible', false);

    // 重置状态
    fileList.value = [];
    previewData.value = [];

    message.success(
      `导入完成，成功${data.success_count}条，失败${data.fail_count}条`,
    );
  } catch (error) {
    message.error('导入失败');
    emit('error', error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <VbenModal
    :visible="visible"
    title="BOM导入"
    :width="600"
    :loading="loading"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <div class="mb-4">
      <Alert
        message="BOM导入说明"
        description="请按照模板格式填写BOM数据，支持Excel文件格式(.xlsx, .xls)。"
        type="info"
        show-icon
      />
    </div>

    <div class="mb-4">
      <VbenButton type="primary" @click="handleDownloadTemplate">
        下载导入模板
      </VbenButton>
    </div>

    <Form.Item label="选择文件">
      <Upload
        v-model:file-list="fileList"
        :max-count="1"
        :before-upload="beforeUpload"
        accept=".xlsx,.xls"
        :custom-request="customRequest"
      >
        <VbenButton>
          <UploadOutlined />
          选择文件
        </VbenButton>
      </Upload>
    </Form.Item>

    <div v-if="fileList.length > 0" class="mb-4">
      <Descriptions :column="1" bordered>
        <DescriptionsItem label="文件名">
          {{ fileList[0]?.name || '' }}
        </DescriptionsItem>
        <DescriptionsItem label="文件大小">
          {{ formatFileSize(fileList[0]?.size || 0) }}
        </DescriptionsItem>
      </Descriptions>
    </div>

    <div v-if="previewData.length > 0" class="mb-4">
      <h4>数据预览 (前10条)</h4>
      <VxeGrid v-bind="previewGridOptions" :data="previewData" height="300" />
    </div>
  </VbenModal>
</template>
